package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.bean.School;
import com.tsinghuabigdata.edu.ddmath.commons.http.AppAsyncTask;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.fragment.MyBaseFragment;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.requestHandler.LoginReqService;
import com.tsinghuabigdata.edu.ddmath.requestHandler.requestImpl.LoginReqImpl;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.ValidatorUtils;
import com.tsinghuabigdata.edu.ddmath.view.FragmentActionbarView;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;

import java.util.ArrayList;
import java.util.List;

import roboguice.inject.InjectView;


/**
 * 个人信息补充界面
 * Created by Administrator on 2016/12/14.
 */

public class UserInfoSuplementFragment extends MyBaseFragment implements View.OnClickListener {
    private static final String TAG = "UserInfoSuplementFragment";
    private View root;
    private Button btEnterdoudou;

    @InjectView(R.id.et_reallyname)
    private EditText etReallyName;
    @InjectView(R.id.et_school)
    private AutoCompleteTextView etSchool;
    @InjectView(R.id.et_encrollyears)
    private EditText etEncrollyears;

    @InjectView(R.id.fr_actionbar)
    private FragmentActionbarView fragmentActionbarView;

    private MyProgressDialog progressDialog;

    private LoginReqService loginReqService = new LoginReqImpl();
    private QueryBlurSchoolTask blurSchoolQueryTask;

    private List<String> schoolNames;
    private List<School> schoolList;


    private ArrayAdapter schoolAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_userinfo_suplement, container, false);
        return root;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        btEnterdoudou = (Button) root.findViewById(R.id.bt_enterdoudou);
        btEnterdoudou.setOnClickListener(this);

        fragmentActionbarView = (FragmentActionbarView) root.findViewById(R.id.fr_actionbar);
        fragmentActionbarView.setLeftTitle("取消");
        fragmentActionbarView.setTitle("个人信息");

        //actionbar listener
        View.OnClickListener actionbarListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.left_icon:
                    case R.id.bar_left_btn:
//                        AlertManager.toast(getActivity(), "left");
                        finish();
                        break;
                    case R.id.right_icon:
                    case R.id.bar_right_btn:
                        break;
                }
            }
        };
        fragmentActionbarView.setListener(actionbarListener);

        progressDialog = new MyProgressDialog(getContext());

//        etSchool.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (blurSchoolQueryTask != null) {
//                    blurSchoolQueryTask.cancel(true);
//                }
//                blurSchoolQueryTask = new QueryBlurSchoolTask(new RequestListener<List<School>>() {
//                    @Override
//                    public void onSuccess(List<School> res) {
//                        blurSchoolQueryTask = null;
//                        schoolList = res;
//                        refreshSchoollist();
//                    }
//
//                    @Override
//                    public void onFail(HttpResponse response, Exception ex) {
//                        blurSchoolQueryTask = null;
//                    }
//                });
////                AlertManager.toast(getContext(), s.toString());
//                blurSchoolQueryTask.execute(s.toString());
//            }
//        });
    }

    private void initData() {
//        schoolNames = new ArrayList<String>();
//        schoolAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, schoolNames);
//        etSchool.setAdapter(schoolAdapter);

    }

    public void refreshSchoollist() {
        schoolNames.clear();
        if (schoolList != null) {
            for (School school : schoolList) {
                schoolNames.add(school.getName());
            }
        }
        schoolAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, schoolNames);
        etSchool.setAdapter(schoolAdapter);
        schoolAdapter.notifyDataSetChanged();
    }

    private String getSchoolId(String schoolName) {
        if (schoolList != null) {
            for (School school : schoolList) {
                if (school.getName().equals(schoolName)) {
                    return school.getSchoolId();
                }
            }
        }
        return "";
    }

    /**
     * 学校模糊查询
     */
    public class QueryBlurSchoolTask extends AppAsyncTask<String, Void, List<School>> {
        private RequestListener reqListener;

        public QueryBlurSchoolTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected List<School> doExecute(String... params) throws Exception {
            String schoolName = params[0];
            return loginReqService.queryBlurSchool(schoolName);
        }

        @Override
        protected void onResult(List<School> resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<List<School>> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (blurSchoolQueryTask != null) {
            blurSchoolQueryTask.cancel(true);
            blurSchoolQueryTask = null;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_enterdoudou:
                //对入学年份进行验证
                String encrollYears = etEncrollyears.getText().toString().trim();
                if (!ValidatorUtils.validateEncrollYears(encrollYears)) {
                    etEncrollyears.setError("请按照格式:20**（纯数字）输入入学年份");
                    return;
                }
                enterDoudou();
                break;
        }
    }

    private void enterDoudou() {
        //补充个人信息
        String reallyname = etReallyName.getText().toString().trim();
        String schoolName = etSchool.getText().toString().trim();
        String encrollyears = etEncrollyears.getText().toString().trim();
//        String schoolId = getSchoolId(schoolName);
        if (TextUtils.isEmpty(reallyname) && TextUtils.isEmpty(encrollyears)) {
            //直接进入
            finish();
            goFragment(new UsercenterFragment());
        } else {
            //将个人信息更新到服务器
            String accessToken = AccountUtils.getLoginUser().getAccessToken();
            String accountId = AccountUtils.getLoginUser().getAccountId();
            progressDialog.setMessage("更新信息中...");
            progressDialog.show();
            new LoginModel().updateExtraPersoninfo(accessToken, accountId, reallyname, encrollyears, new RequestListener() {
                @Override
                public void onSuccess(Object res) {
                    progressDialog.dismiss();
                    finish();
                    goFragment(new UsercenterFragment());
                }

                @Override
                public void onFail(HttpResponse response, Exception ex) {
                    AlertManager.showErrorInfo(getContext(), ex);
                    progressDialog.dismiss();
                }
            });
        }
    }
}
